package com.example.chcrm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.chcrm.entity.common.*;
import com.example.chcrm.entity.employee.Department;
import com.example.chcrm.entity.employee.EmployeeVo;
import com.example.chcrm.entity.employee.EssEmployee;
import com.example.chcrm.entity.employee.RoleModels;
import com.example.chcrm.service.EssEmployeeService;
import com.example.chcrm.service.EssRoleMenuService;
import com.example.chcrm.service.RoleModelsService;
import com.example.chcrm.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * @Author 邹
 * @Date 2025/4/18 21:41
 * @Version 1.0
 */
@RestController
@RequestMapping("/role")
@CrossOrigin // 允许跨域访问
public class RoleModelsController {
    @Autowired
    RoleModelsService roleModelsService;
    @Autowired
    EssRoleMenuService essRoleMenuService;
    @Autowired
    private RoleService roleservice;
    /**
     * 查询所有角色
     *
     * essEmployee
     * @return
     */
    @GetMapping("/selectAllRole")
    public ResponseMsg<Object> selectAllRole() {
        return roleModelsService.selectAllRole();
    }

    /**
     * 查询角色
     *
     * essEmployee
     * @return
     */
    @PostMapping("/pageList")
    public ResponseMsg<IPage<RoleModels>> pageList(@RequestBody RoleModels roleModels) {
        return roleModelsService.pageList(roleModels);
    }

    /**
     * 角色新增
     */
    @PostMapping("/add")
    public ResponseMsg<Object> add(@RequestBody RoleModels roleModels) {

        return  roleModelsService.add(roleModels);
    }

    /**
     * 角色禁用/启用
     */
    @PostMapping("/disable")
    public ResponseMsg<Object> disable(@RequestBody RoleModels roleModels) {

        return  roleModelsService.disable(roleModels);
    }


    /**
     * 角色修改
     */
    @PostMapping("/update")
    public ResponseMsg<Object> update(@RequestBody RoleModels roleModels) {
        return  roleModelsService.update(roleModels);
    }

    /**
     * 角色删除
     */
    @GetMapping("/delete/{id}")
    public ResponseMsg<Object> delete(@PathVariable String id) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        if (id == null || id.equals("")) {
            msg.fail("删除失败ID不能为空");
            return msg;
        }
        return roleModelsService.delete(id);
    }

    @GetMapping("/seAllMenu")
    public ResponseMsg<List<Object>> seAllMenu(){
        ResponseMsg<List<Object>> resp = new ResponseMsg<>();
        HttpServletRequest request = ServletUtils.getRequest();
        Map<String, String> map = ServletUtils.getHeaders(request);
        String empVoHeader=null;
        if (map !=null) {
            empVoHeader = map.get("empvo");
        }
        EmployeeVo empVo = new EmployeeVo();
        if (StringUtils.isNotBlank(empVoHeader)) {
            // 1. URL安全BASE64解码
            String base64 = empVoHeader.replace('-', '+').replace('_', '/');
            byte[] decodedBytes = Base64.getDecoder().decode(base64);
            // 2. UTF-8解码
            String empNm = new String(decodedBytes, StandardCharsets.UTF_8);
//            empNm = empNm.replaceAll("^\"|\"$", "").trim();  // 关键修复
            empVo.setEmpNm(empNm);
        }
        if (!StringUtils.isNotBlank(empVo.getEmpNm())){
            resp.fail("未检索到登录用户");
            return resp;
        }
//        return resp;
        return essRoleMenuService.seAllMenu(empVo);
    }

    //获取该角色的菜单权限
    @GetMapping("/getMenuByRoleId/{id}")
    public ResponseMsg<Object> getMenuByRoleId(@PathVariable String id) {
        ResponseMsg<Object> responseMsg = new ResponseMsg<>();
        try{
            List<Object> menuByRoleId = essRoleMenuService.getMenuByRoleId(id);
            responseMsg.setData(menuByRoleId);
            responseMsg.success("查询成功");
        }catch (Exception e){
            responseMsg.fail("查询失败");
        }
        return  responseMsg;
    }

    //获取该角色的菜单权限
    @PostMapping("/updateMenuByRole")
    @Transactional
    public ResponseMsg<Object> addMenu(@RequestBody Roles roles) {
        ResponseMsg<Object> resp = new ResponseMsg<>();
        try {
            String menuId = roles.getMenuIds();
            String roleId = roles.getRoleId();
            List<EssRoleMenu> list = new ArrayList<EssRoleMenu>();
            // 角色
            String arr [] = roleId.split(",");
            // 菜单ID
            String str [] = menuId.split(",");
            // 删除关联
            essRoleMenuService.deletesRoleMenuById(arr);
            for (int i = 0; i < arr.length; i++) {
                for (int j = 0; j < str.length; j++) {
                    EssRoleMenu rome = new EssRoleMenu();
                    rome.setId(RandomHelper.uuid());
                    rome.setRoleId(arr[i]);
                    rome.setMenuId(str[j]);
                    rome.setVersion(1);
                    list.add(rome);
                }
            }
            if ( !(menuId.length()==0 || roles.getMenuIds().equals(""))) {
                essRoleMenuService.setRoleResource(list);
            }
            resp.setMessage("修改菜单成功！");
            resp.setStatus(0);
//            List<EssRoleMenu> aclResources = roleservice.findAllRoleMeun();
        } catch (Exception e) {
            e.printStackTrace();
            resp.fail("修改菜单异常！");
        }
        return resp;
    }
}
